# -*- coding: utf-8 -*-
import paramiko
import os
import sys
import datetime
import ConfigParser
config = ConfigParser.RawConfigParser()

ROOT = os.path.dirname(os.path.realpath(__file__))

RED = "\033[1;31m"
BLUE = "\033[1;34m"
CYAN = "\033[1;36m"
GREEN = "\033[0;32m"
RESET = "\033[0;0m"
BOLD = "\033[;1m"
REVERSE = "\033[;7m"

config.read(os.path.join(ROOT, "../config/server.ini"))

print ROOT, "../config/server.ini"

a = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
#生成包名
a = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')

sys.stdout.write(GREEN)
print("="*80)
print("当前为正式服务器的部署请注意")
print("="*80)
try:
    name = raw_input("请输入要重启的服务器代号(具体的参见config目录下的server.ini:")

    print name
    ip = config.get(name, 'ip')
    port = config.getint(name, 'port')
    username = config.get(name, 'user')
    password = config.get(name, 'password')

    d = config.get(name, 'framework')
    gamename = config.get(name, 'gamename')
    serverfolder = None
    if config.has_option(name, 'serverfolder'):
        serverfolder = config.get(name, 'serverfolder')

    s = """
        chmod 777 build%s.sh
        sh build%s.sh %s %s
    """ % (d, d, gamename, a)
    filename = gamename+"bin_"+a+".tar.gz"
    print s

    os.system(s)

    print '准备开始连接服务器:' + ip, port, username, password
    print 'IP:' + ip
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, port, username, password)

    tran = paramiko.Transport((ip, port))
    tran.connect(username=username, password=password)

    sftp = paramiko.SFTPClient.from_transport(tran)

    print "上传文件", filename
    sftp.put("./out/"+filename, "/data/proj/%s" % (filename))
    sftp = paramiko.SFTPClient.from_transport(tran)

    tran.close()

    print "解压缩文件"
    s = """
            cd ~
            cd /data/proj
            tar -zxf %s
            cd /data/proj/%sbin/%s
            `pwd`

        """ % (filename, d, name)
    stdin, stdout, stderr = ssh.exec_command(s)
    pass

    ssh.close()
except Exception as e:
    print e
    # raise
else:
    pass
finally:
    pass
